<!doctype html>
<html lang="en">

<head>
	<title>GET VIDEO</title>
	<meta charset="utf-8">
	<style type="text/css">
		#canvas {
			background-color: chartreuse;
		}
	</style>
</head>

<body>
	<span>输入宽度：<input type="text" id="v_width" value="500"></span>

    <span>
        输入高度：<input type="text" id="v_height" value="250">
    </span>

    <input type="button" title="开启摄像头" value="开启摄像头" onclick="getMedia()" />
    <video id="video" width="500px" height="250px" autoplay="autoplay" style="background-color: blue;"></video>
    <canvas id="canvas" width="500px" height="250px"></canvas>
    <button id="snap" onclick="takePhoto()">拍照</button>

    <div>
        <button id="position" onclick="positionNumber()">定位数字笔画</button>
        <button id="distance" onclick="calculateDistance()">定位数字间距</button>
        输入数字个数：<input type="text" id="numberDigits" value="4">
        亮度阈值：<input type="text" id="threshHold" value="170">
        <br>
        检测间隔：<input type="text" id="detectInterval"" value=" 10">
        <span id="finishShape"></span>
        <span id="finishDistance"></span>
    </div>
    <div>
        <button id="start" onclick="startDetectNumber()">开始检测数据</button>
    </div>
    <div>
        <h3 id="result" >结果</h3>
            
    </div>
    <script>
        //定义数字：
        let Number0 = 0b01110111;
        let Number1 = 0b01100000;
        let Number2 = 0b00111110;
        let Number3 = 0b01111100;
        let Number4 = 0b01101001;
        let Number5 = 0b01011101;
        let Number6 = 0b01011111;
        let Number7 = 0b01100100;
        let Number8 = 0b01111111;
        let Number9 = 0b01111101;

        let resultNumber;
        //定义笔画变量
        let numberX = [];
        let numberY = [];
        let isPositionNumber = false;
        let distanceX = [];
        let distanceY = [];
        let xDistantce;
        let yDistance;
        let isCaculateDistance = false;
        //定义点击次数：
        let clickCount = 0;
        //定义点击坐标
        let clickPos = [];
        //获得video摄像头区域
        let video = document.getElementById("video");
        v_width = document.getElementById("v_width");
        v_height = document.getElementById("v_height");
        let canvas = document.getElementById("canvas");
        //拿到存放结果的容器对象
        let resultContainer = document.getElementById("result");
        //延时睡眠函数
        var sleep = function (time) {
            var startTime = new Date().getTime() + parseInt(time, 10);
            while (new Date().getTime() < startTime) { }
        };
        function getMedia() {
            video.width = v_width.value;
            video.height = v_height.value;
            let constraints = {
                video: { width: {exact: v_width.value}, height: {exact: v_height.value}, facingMode: { exact: 'environment'}},
                audio: false
                
            };
            /*
            这里介绍新的方法:H5新媒体接口 navigator.mediaDevices.getUserMedia()
            这个方法会提示用户是否允许媒体输入,(媒体输入主要包括相机,视频采集设备,屏幕共享服务,麦克风,A/D转换器等)
            返回的是一个Promise对象。
            如果用户同意使用权限,则会将 MediaStream对象作为resolve()的参数传给then()
            如果用户拒绝使用权限,或者请求的媒体资源不可用,则会将 PermissionDeniedError作为reject()的参数传给catch()
            */
            let promise = navigator.mediaDevices.getUserMedia(constraints);
            promise.then(function (MediaStream) {
                video.srcObject = MediaStream;
                video.play();
                setTimeout(() => {
                    MediaStream.getTracks().forEach((track)=>{
                        track.stop();
                    })
                }, 6000);

            }).catch(function (PermissionDeniedError) {
                console.log(PermissionDeniedError);
            })
        }
        function takePhoto() {
            //获得Canvas对象
            //let canvas = document.getElementById("canvas");
            canvas.width = v_width.value;
            canvas.height = v_height.value;

            let ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, v_width.value, v_height.value);
        }
        canvas.onclick = function (e) {
            if (isPositionNumber == true && clickCount < 7) {
                if (e.offsetX || e.layerX) {
                    numberX[clickCount] = e.offsetX == undefined ? e.layerX : e.offsetX;
                    numberY[clickCount] = e.offsetY == undefined ? e.layerY : e.offsetY;
                    console.log(numberX, numberY);
                }
                clickCount += 1;
                if (clickCount == 7) {
                    console.log("已够7笔，退出笔画定位模式");
                    clickCount = 0;
                    isPositionNumber = false;
                    document.getElementById("finishShape").innerHTML = "已完成笔画";
                    return;
                }
                return;
            }
            else if (isPositionNumber == true && clickCount >= 7) {
                console.log("已经够7笔笔画")
                clickCount = 0;
                return;
            }
            if (isCaculateDistance == true && clickCount < 2) {
                if (e.offsetX || e.layerX) {
                    distanceX[clickCount] = e.offsetX == undefined ? e.layerX : e.offsetX;
                    distanceY[clickCount] = e.offsetY == undefined ? e.layerY : e.offsetY;
                    console.log(distanceX, distanceY);
                }
                clickCount += 1;
                if (clickCount == 2) {
                    xDistantce = distanceX[1] - distanceX[0];
                    yDistance = distanceY[1] - distanceY[0];
                    console.log("已够2笔，退出笔画定位模式,x,y距离分别为", xDistantce, yDistance);
                    clickCount = 0;
                    document.getElementById("finishDistance").innerHTML = "已完成间距设置";
                    isCaculateDistance = false;
                    return;
                }
                return;
            }
            else if (isCaculateDistance == true && clickCount >= 2) {
                console.log("已经够2笔笔画")
                clickCount = 0;
                return;
            }
            else if (isPositionNumber == false && isCaculateDistance == false) {
                console.log("没有在点击定位模式");
                return;
            }

        }
        function positionNumber() {
            if (clickCount < 7 && isPositionNumber == false) {
                console.log("开始定位笔画")
                document.getElementById("finishShape").innerHTML = "";
                isPositionNumber = true;
            }
            else {
                isPositionNumber = false;
                clickCount = 0;
                return;
            }
        }
        //定位间距的函数
        function calculateDistance() {
            if (clickCount < 7 && isCaculateDistance == false) {
                console.log("开始计算X距离")
                document.getElementById("finishDistance").innerHTML = "";
                isCaculateDistance = true;
            }
            else {
                isCaculateDistance = false;
                clickCount = 0;
                return;
            }
        }
        //检测数字函数
        function startDetectNumber() {
            //设定间隔，每多少s检测一次
            setInterval(() => {
                //开启摄像头，5S后自动关闭
                getMedia();
                //延时2秒后执行后续动作
                setTimeout(() => {
                    //拍摄照片
                    takePhoto();
                    //探测数字
                    detectNumber();
                    //关闭摄像头
                //     video.srcObject.getTracks().forEach(track => {
                //         track.stop();
                //     })

                    //输出值到结果容器对象
                    console.log("结果是：", resultNumber);
                    resultContainer.innerHTML = resultNumber;
                 }, 4000);



            }, document.getElementById("detectInterval").value * 1000);

        }

        //检测数字结果的函数
        function detectNumber() {
            //定义一个临时数
            let tempNumber = 0;
            let digitsQty = 0;
            //拿到数字位数
            digitsQty = document.getElementById("numberDigits").value;
            // 循环多少次表示有多少位数字
            for ( let i = 0;i < digitsQty;i++){
                //各位数乘以相应进位后叠加起来
                tempNumber += detectDigit(i) * (((digitsQty - i - 1)==0) ? 1 : (Math.pow(10,(digitsQty - i - 1) )) ) ;
            }
            resultNumber = tempNumber;
        }

        //检测某一位数的函数
        function detectDigit(digit) {
            //定义一个临时数
            let temp = 0;
            let colorTemp;
            //定义阈值、数字数
            let threshHold;

            //拿到阈值
            threshHold = document.getElementById("threshHold").value;

            //拿到画布数据
            let ctx = canvas.getContext("2d");

            //循环7次，因为有7个笔画
            for (let i = 0; i < 7; i++){
                //拿到颜色数据
                colorTemp = ctx.getImageData(numberX[i]+xDistantce*digit, numberY[i]+yDistance*digit, 1, 1).data;
                //与阈值对比然后移位
                if (colorTemp[0] > threshHold || colorTemp[1] > threshHold || colorTemp[2] > threshHold){
                    //如果RGB任意一个超过阈值，就+1然后左移一位
                    temp = temp + 1;
                }
                //如果没有到6就左移一位
                if (i < 6 ){
                    temp = temp << 1;
                }
 

            }
            //输出temp值看看
            console.log("第%d位数是",digit,temp);

            //拿完一个数字的数组后与既定数组对比
           if (temp == Number0){
               return 0;
           }
           else if (temp == Number1){
               return 1;
           }
           else if (temp == Number2){
               return 2;
           }
           else if (temp == Number3){
               return 3;
           }
           else if (temp == Number4){
               return 4;
           }
           else if (temp == Number5){
               return 5;
           }
           else if (temp == Number6){
               return 6;
           }
           else if (temp == Number7){
               return 7;
           }
           else if (temp == Number8){
               return 8;
           }
           else if (temp == Number9){
               return 9;
           }
        }
    </script>
</body>


</html>